package com.huiquan.framework.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShellUtils {

	private static final Logger LOG = LoggerFactory.getLogger(ShellUtils.class);

	public static String executeShell(String[] args) throws IOException {

		LOG.info("Execute shell's name is " + args[1]);
		StringBuffer param = new StringBuffer();
		if (args.length > 2) {
			for (int i = 2; i < args.length; i++) {
				param.append("[");
				param.append(args[i]);
				param.append("],");
			}
			LOG.info("param is " + param.toString());
		}

		Map<String, String> env = new HashMap<String, String>(System.getenv());
		env.put("PYTHONIOENCODING", "utf-8");
		String[] envp = new String[env.size()];
		int count = 0;
		for (Map.Entry<String, String> entry : env.entrySet()) {
			envp[count++] = entry.getKey() + "=" + entry.getValue();
		}
		// 执行shell脚本
		Process pcs = Runtime.getRuntime().exec(args, envp);

		// 定义shell返回值
		StringBuffer result = new StringBuffer();

		// 获取shell返回流
		BufferedInputStream in = new BufferedInputStream(pcs.getInputStream());
		// 字符流转换字节流
		BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));

		// 输出文本日志
		String lineStr;
		while ((lineStr = br.readLine()) != null) {
			result.append(lineStr);
		}
		// 关闭输入流
		br.close();
		in.close();
		InputStream stderr = pcs.getErrorStream();
		br = new BufferedReader(new InputStreamReader(stderr, "utf-8"));
		while ((lineStr = br.readLine()) != null) {
			result.append(lineStr);
		}

		LOG.info("Execute shell result:\n" + result);

		return result.toString();
	}
}
